<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>需求管理系统</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: #f5f5f5;
        }

        .maintenance-container {
            display: flex;
            height: 100vh;
        }

        .left-nav {
            width: 250px;
            background: #fff;
            padding: 20px;
            border-right: 1px solid #e0e0e0;
        }

        .dropdown {
            position: relative;
            margin-bottom: 15px;
            padding: 12px;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            user-select: none;
        }

        .dropdown:hover {
            background: #e9ecef;
        }

        .dropdown-content {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
        }

        .dropdown-content div {
            padding: 10px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }

        .dropdown-content div:hover {
            background: #f8f9fa;
        }

        .dropdown-content div:last-child {
            border-bottom: none;
        }

        .dropdown.active .dropdown-content {
            display: block;
        }

        .option {
            padding: 12px;
            margin-bottom: 10px;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .option:hover, .option.active {
            background: #007bff;
            color: white;
        }

        .right-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .overview {
            margin-bottom: 20px;
        }

        .horizontal-layout {
            display: flex;
            gap: 20px;
            height: calc(100vh - 150px);
        }

        .mind-map, .description {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .description textarea {
            width: 100%;
            height: calc(100% - 40px);
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            font-family: inherit;
            font-size: 14px;
            resize: none;
            outline: none;
        }

        .description textarea:focus {
            border-color: #007bff;
        }

        .mind-map-content {
            height: calc(100% - 40px);
            border: 1px dashed #ddd;
            border-radius: 4px;
            padding: 20px;
            overflow-y: auto;
        }

        .mind-map-content.empty {
            display: grid;
            place-items: center;
            color: #999;
        }

        .button-group {
            margin: 15px 0;
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .btn:hover {
            background: #0056b3;
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .loading {
            color: #666;
            font-style: italic;
        }

        .sub-demands-list {
            margin-top: 20px;
        }

        .sub-demand-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .sub-demand-item:hover {
            background: #e9ecef;
            border-color: #007bff;
        }

        .sub-demand-item.active {
            background: #e3f2fd;
            border-color: #2196f3;
        }

        .sub-demand-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .sub-demand-preview {
            color: #666;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .markdown-content {
            line-height: 1.6;
        }

        .markdown-content h1, .markdown-content h2, .markdown-content h3 {
            margin: 20px 0 10px 0;
            color: #333;
        }

        .markdown-content h1 { font-size: 24px; }
        .markdown-content h2 { font-size: 20px; }
        .markdown-content h3 { font-size: 16px; }

        .markdown-content ul, .markdown-content ol {
            margin: 10px 0;
            padding-left: 20px;
        }

        .markdown-content li {
            margin: 5px 0;
        }

        .markdown-content code {
            background: #f8f9fa;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }

        .markdown-content pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
            margin: 10px 0;
        }
    </style>
</head>
<body>
<div class="maintenance-container">
    <div class="left-nav">
        <div class="dropdown main-demand-dropdown" id="mainDemandDropdown">
            选择已发布的需求
            <div class="dropdown-content" id="mainDemandList">
                <!-- 动态加载需求列表 -->
            </div>
        </div>
        <div class="dropdown sub-demand-dropdown" id="subDemandDropdown">
            下拉选择子需求
            <div class="dropdown-content" id="subDemandList">
                <!-- 动态加载子需求列表 -->
            </div>
        </div>
        <div class="option active" id="overview-option">概览</div>
        <div class="option" id="sub-demand-option">子需求</div>
    </div>
    <div class="right-content">
        <div class="overview">
            <h3 style="margin-bottom: 12px; color: #333" id="overviewTitle">
                选择一个需求查看概览
            </h3>
            <div class="button-group">
                <button class="btn" id="generateSubDemandsBtn" disabled>生成子需求</button>
                <button class="btn" id="refreshDemandsBtn">刷新需求列表</button>
            </div>
        </div>

        <div class="horizontal-layout">
            <div class="mind-map">
                <h3 style="margin-bottom: 12px; color: #333">需求脑图</h3>
                <div class="mind-map-content empty" id="mindMapContent">
                    脑图区域（选择需求后自动生成）
                </div>
            </div>

            <div class="description">
                <h3 style="margin-bottom: 12px; color: #333">需求描述</h3>
                <textarea id="demandDescription" placeholder="请选择需求查看详细描述..." readonly></textarea>
            </div>
        </div>

        <div class="sub-demands-list" id="subDemandsList" style="display: none;">
            <h3 style="margin-bottom: 15px; color: #333">子需求列表</h3>
            <div id="subDemandsContent">
                <!-- 动态生成子需求列表 -->
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentUserId = 'abc-123'; // 可以从登录状态或其他地方获取
    let currentDemandId = null;
    let currentSubDemands = [];
    let selectedSubDemandId = null;

    // DOM 元素
    const mainDemandDropdown = document.getElementById('mainDemandDropdown');
    const mainDemandList = document.getElementById('mainDemandList');
    const subDemandDropdown = document.getElementById('subDemandDropdown');
    const subDemandList = document.getElementById('subDemandList');
    const overviewTitle = document.getElementById('overviewTitle');
    const mindMapContent = document.getElementById('mindMapContent');
    const demandDescription = document.getElementById('demandDescription');
    const generateSubDemandsBtn = document.getElementById('generateSubDemandsBtn');
    const refreshDemandsBtn = document.getElementById('refreshDemandsBtn');
    const subDemandsList = document.getElementById('subDemandsList');
    const subDemandsContent = document.getElementById('subDemandsContent');
    const overviewOption = document.getElementById('overview-option');
    const subDemandOption = document.getElementById('sub-demand-option');

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadDemands();
        setupEventListeners();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 主需求下拉框点击
        mainDemandDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleDropdown(mainDemandDropdown);
        });

        // 子需求下拉框点击
        subDemandDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleDropdown(subDemandDropdown);
        });

        // 生成子需求按钮
        generateSubDemandsBtn.addEventListener('click', generateSubDemands);

        // 刷新按钮
        refreshDemandsBtn.addEventListener('click', loadDemands);

        // 选项卡切换
        overviewOption.addEventListener('click', () => switchTab('overview'));
        subDemandOption.addEventListener('click', () => switchTab('sub-demand'));

        // 点击其他地方关闭下拉框
        document.addEventListener('click', function() {
            closeAllDropdowns();
        });
    }

    // 切换下拉框状态
    function toggleDropdown(dropdown) {
        closeAllDropdowns();
        dropdown.classList.toggle('active');
    }

    // 关闭所有下拉框
    function closeAllDropdowns() {
        document.querySelectorAll('.dropdown').forEach(dropdown => {
            dropdown.classList.remove('active');
        });
    }

    // 切换选项卡
    function switchTab(tab) {
        document.querySelectorAll('.option').forEach(option => {
            option.classList.remove('active');
        });

        if (tab === 'overview') {
            overviewOption.classList.add('active');
            subDemandsList.style.display = 'none';
            document.querySelector('.horizontal-layout').style.display = 'flex';
        } else {
            subDemandOption.classList.add('active');
            subDemandsList.style.display = 'block';
            document.querySelector('.horizontal-layout').style.display = 'none';
        }
    }

    // 加载用户需求列表
    async function loadDemands() {
        try {
            refreshDemandsBtn.textContent = '加载中...';
            refreshDemandsBtn.disabled = true;

            // 注意：这里需要替换实际的用户ID
            const response = await fetch(`http://localhost:8080/api/demands/creator/${currentUserId}/list`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const demands = await response.json();
            displayDemandsList(demands);

        } catch (error) {
            console.error('加载需求列表失败:', error);
            alert('加载需求列表失败，请检查网络连接或联系管理员');
        } finally {
            refreshDemandsBtn.textContent = '刷新需求列表';
            refreshDemandsBtn.disabled = false;
        }
    }

    // 显示需求列表
    function displayDemandsList(demands) {
        mainDemandList.innerHTML = '';

        if (demands.length === 0) {
            mainDemandList.innerHTML = '<div style="padding: 10px; color: #999;">暂无需求</div>';
            return;
        }

        demands.forEach(demand => {
            const demandItem = document.createElement('div');
            demandItem.setAttribute('data-demand-id', demand.id);
            demandItem.innerHTML = `
                    <div style="font-weight: bold;">${demand.title}</div>
                    <div style="font-size: 12px; color: #666; margin-top: 2px;">
                        状态: ${getStatusText(demand.status)} | 创建时间: ${formatDate(demand.createdTime)}
                    </div>
                `;
            demandItem.addEventListener('click', (e) => {
                e.stopPropagation();
                selectDemand(demand.id, demand.title);
            });
            mainDemandList.appendChild(demandItem);
        });
    }

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'DRAFT': '草稿',
            'PUBLISHED': '已发布',
            'ARCHIVED': '已归档'
        };
        return statusMap[status] || status;
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 选择需求
    async function selectDemand(demandId, demandTitle) {
        try {
            currentDemandId = demandId;
            overviewTitle.textContent = `${demandTitle} 的概览`;
            generateSubDemandsBtn.disabled = false;

            // 更新主需求下拉框显示
            mainDemandDropdown.childNodes[0].textContent = demandTitle;
            closeAllDropdowns();

            // 加载需求详情
            await loadDemandDetails(demandId);

        } catch (error) {
            console.error('选择需求失败:', error);
            alert('加载需求详情失败');
        }
    }

    // 加载需求详情
    async function loadDemandDetails(demandId) {
        try {
            const response = await fetch(`http://localhost:8080/api/demands/${demandId}/details`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const demandDetail = await response.json();
            displayDemandDetails(demandDetail);

        } catch (error) {
            console.error('加载需求详情失败:', error);
            demandDescription.value = '加载需求详情失败，请重试';
        }
    }

    // 显示需求详情
    function displayDemandDetails(demandDetail) {
        // 显示需求描述
        demandDescription.value = demandDetail.description || '暂无描述';

        // 生成并显示思维导图
        generateMindMap(demandDetail.description);
    }

    // 生成思维导图
    function generateMindMap(markdownContent) {
        if (!markdownContent) {
            mindMapContent.innerHTML = '暂无内容生成脑图';
            mindMapContent.className = 'mind-map-content empty';
            return;
        }

        try {
            // 使用 marked 库将 Markdown 转换为 HTML
            const htmlContent = marked.parse(markdownContent);

            // 创建思维导图结构
            const mindMapHtml = createMindMapFromMarkdown(markdownContent);

            mindMapContent.innerHTML = mindMapHtml;
            mindMapContent.className = 'mind-map-content markdown-content';

        } catch (error) {
            console.error('生成思维导图失败:', error);
            mindMapContent.innerHTML = '生成思维导图失败';
            mindMapContent.className = 'mind-map-content empty';
        }
    }

    // 从 Markdown 创建思维导图结构
    function createMindMapFromMarkdown(markdown) {
        const lines = markdown.split('\n');
        let html = '';
        let currentLevel = 0;

        lines.forEach(line => {
            const trimmedLine = line.trim();
            if (!trimmedLine) return;

            // 检测标题级别
            const headingMatch = trimmedLine.match(/^(#{1,6})\s+(.+)$/);
            if (headingMatch) {
                const level = headingMatch[1].length;
                const title = headingMatch[2];
                const indent = (level - 1) * 20;

                html += `<div style="margin-left: ${indent}px; margin: 10px 0 5px ${indent}px; font-weight: bold; color: #333; font-size: ${20 - level}px;">${title}</div>`;
                currentLevel = level;
            } else if (trimmedLine.startsWith('- ') || trimmedLine.startsWith('* ')) {
                // 列表项
                const content = trimmedLine.substring(2);
                const indent = (currentLevel) * 20 + 15;
                html += `<div style="margin-left: ${indent}px; margin: 5px 0; color: #666; font-size: 14px;">• ${content}</div>`;
            } else if (trimmedLine.startsWith('**') && trimmedLine.endsWith('**')) {
                // 粗体文本
                const content = trimmedLine.slice(2, -2);
                const indent = currentLevel * 20;
                html += `<div style="margin-left: ${indent}px; margin: 5px 0; font-weight: bold; color: #555;">${content}</div>`;
            } else if (trimmedLine.length > 0) {
                // 普通文本
                const indent = currentLevel * 20;
                html += `<div style="margin-left: ${indent}px; margin: 3px 0; color: #777; font-size: 13px;">${trimmedLine}</div>`;
            }
        });

        return html || '无法解析内容';
    }

    // 生成子需求
    async function generateSubDemands() {
        if (!currentDemandId) {
            alert('请先选择一个需求');
            return;
        }

        try {
            generateSubDemandsBtn.textContent = '生成中...';
            generateSubDemandsBtn.disabled = true;

            // 获取当前需求的描述作为查询内容
            const query = demandDescription.value || '生成子需求';

            const requestData = {
                inputs: {},
                query: query,
                response_mode: "streaming",
                conversation_id: "",
                user: currentUserId,
                files: []
            };

            const response = await fetch('http://localhost:8080/api/child-requirements', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            displaySubDemands(result);

        } catch (error) {
            console.error('生成子需求失败:', error);
            alert('生成子需求失败，请重试');
        } finally {
            generateSubDemandsBtn.textContent = '生成子需求';
            generateSubDemandsBtn.disabled = false;
        }
    }

    // 显示子需求
    function displaySubDemands(result) {
        if (!result.sub_requirements || result.sub_requirements.length === 0) {
            alert('未生成任何子需求');
            return;
        }

        currentSubDemands = result.sub_requirements;

        // 更新子需求下拉列表
        updateSubDemandDropdown(result.sub_requirements);

        // 显示子需求列表
        displaySubDemandsList(result.sub_requirements);

        // 切换到子需求选项卡
        switchTab('sub-demand');
    }

    // 更新子需求下拉框
    function updateSubDemandDropdown(subDemands) {
        subDemandList.innerHTML = '';

        subDemands.forEach(subDemand => {
            const subDemandItem = document.createElement('div');
            subDemandItem.setAttribute('data-sub-demand-id', subDemand.id);
            subDemandItem.textContent = subDemand.title;
            subDemandItem.addEventListener('click', (e) => {
                e.stopPropagation();
                selectSubDemand(subDemand.id, subDemand.title, subDemand.description);
            });
            subDemandList.appendChild(subDemandItem);
        });
    }

    // 显示子需求列表
    function displaySubDemandsList(subDemands) {
        subDemandsContent.innerHTML = '';

        subDemands.forEach(subDemand => {
            const subDemandElement = document.createElement('div');
            subDemandElement.className = 'sub-demand-item';
            subDemandElement.setAttribute('data-sub-demand-id', subDemand.id);

            // 提取描述的前50个字符作为预览
            const preview = subDemand.description.replace(/[#*\-\n]/g, ' ').trim().substring(0, 50) + '...';

            subDemandElement.innerHTML = `
                    <div class="sub-demand-title">${subDemand.title}</div>
                    <div class="sub-demand-preview">${preview}</div>
                `;

            subDemandElement.addEventListener('click', () => {
                selectSubDemand(subDemand.id, subDemand.title, subDemand.description);
            });

            subDemandsContent.appendChild(subDemandElement);
        });
    }

    // 选择子需求
    function selectSubDemand(subDemandId, subDemandTitle, subDemandDescription) {
        selectedSubDemandId = subDemandId;

        // 更新子需求下拉框显示
        subDemandDropdown.childNodes[0].textContent = subDemandTitle;
        closeAllDropdowns();

        // 更新右侧内容
        overviewTitle.textContent = `子需求：${subDemandTitle}`;
        demandDescription.value = subDemandDescription;

        // 生成子需求的思维导图
        generateMindMap(subDemandDescription);

        // 高亮选中的子需求项
        document.querySelectorAll('.sub-demand-item').forEach(item => {
            item.classList.remove('active');
        });
        const selectedItem = document.querySelector(`[data-sub-demand-id="${subDemandId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('active');
        }

        // 切换到概览视图
        switchTab('overview');
    }
</script>
</body>
</html>